#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "settingsManager.h"
#include "Settings.h"
#include "logger.h"


extern char  g_conf_path[256];

char  g_local_mqtt_addr[64] = "172.17.0.1";
short g_local_mqtt_port     = 1883;
char  g_local_mqtt_username[16] = "IOT";
char  g_local_mqtt_password[16]  = "(^_^)(-_^)";


/**
 * @brief 初始化配置文件,导入配置
 */
void initSettings(){
    #if 1
    // 判断配置文件路径是否为空
    if(1 > strlen(g_conf_path)){
        log_w("The config file path is empty, use default config file path: ./conf/ped.conf");
        return ;
    }
    // 打开配置文件，如果打开失败
    if(0 > setting_open(g_conf_path)){
        log_w("Open config file failed, use default config file path: ./conf/ped.conf");
        return ;
    }
    char value[256] = {0};
    // 读取配置文件中的local_mqtt_addr，如果读取成功，则将值赋给g_local_mqtt_addr
    if(0 == setting_read("local_mqtt_addr", (char **)&value)){
        snprintf(g_local_mqtt_addr, sizeof(g_local_mqtt_addr), "%s", value);
    }
    // 读取配置文件中的local_mqtt_port，如果读取成功，则将值赋给g_local_mqtt_port
    memset(value, 0, sizeof(value));
    if(0 == setting_read("local_mqtt_port", (char **)&value)){
        int port = atoi(value);
        if(0 < port){
            g_local_mqtt_port = port;
        }
    }
    // 读取配置文件中的local_username，如果读取成功，则将值赋给g_local_mqtt_username
    memset(value, 0, sizeof(value));
    if(0 == setting_read("local_username", (char **)&value)){
        snprintf(g_local_mqtt_username, sizeof(g_local_mqtt_username), "%s", value);
    }
    // 读取配置文件中的local_password，如果读取成功，则将值赋给g_local_mqtt_password
    memset(value, 0, sizeof(value));
    if(0 == setting_read("local_password", (char **)&value)){
        snprintf(g_local_mqtt_password, sizeof(g_local_mqtt_password), "%s", value);
    }
    // 读取配置文件中的log_level，如果读取成功，则将值赋给g_local_mqtt_port
    memset(value, 0, sizeof(value));
    if(0 == setting_read("local_mqtt_port", (char **)&value)){
        int log_level = atoi(value);
        if((0 <= log_level) && (6 > log_level)){
            g_log_level = log_level;
        }
    }
    // 关闭配置文件
    setting_close();
    #endif
}

void setLogLevel(){
    log_set_level(g_log_level);
}
void loadSettings(){
    //读取配置文件
    initSettings();
    //设置日志等级
    setLogLevel();
}